import cv2
import math
import argparse
class FaceDetectionSingleton:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(FaceDetectionSingleton, cls).__new__(cls, *args, **kwargs)
            cls._instance.__init_once()
        return cls._instance

    def __init_once(self):
        # 仅加载一次模型
        faceProto = "/root/Gender-and-Age-Detection/opencv_face_detector.pbtxt"
        faceModel = "/root/Gender-and-Age-Detection/opencv_face_detector_uint8.pb"
        ageProto = "/root/Gender-and-Age-Detection/age_deploy.prototxt"
        ageModel = "/root/Gender-and-Age-Detection/age_net.caffemodel"
        genderProto = "/root/Gender-and-Age-Detection/gender_deploy.prototxt"
        genderModel = "/root/Gender-and-Age-Detection/gender_net.caffemodel"

        # 初始化模型
        self.faceNet = cv2.dnn.readNet(faceModel, faceProto)
        self.ageNet = cv2.dnn.readNet(ageModel, ageProto)
        self.genderNet = cv2.dnn.readNet(genderModel, genderProto)
        self.MODEL_MEAN_VALUES = (78.4263377603, 87.7689143744, 114.895847746)
        self.ageList = ['(0-2)', '(4-6)', '(8-12)', '(15-20)', '(25-32)', '(38-43)', '(48-53)', '(60-100)']
        self.genderList = ['Male', 'Female']

    def detect_age_gender(self, face):
        blob = cv2.dnn.blobFromImage(face, 1.0, (227, 227), self.MODEL_MEAN_VALUES, swapRB=False)
        self.genderNet.setInput(blob)
        genderPreds = self.genderNet.forward()
        gender = self.genderList[genderPreds[0].argmax()]

        self.ageNet.setInput(blob)
        agePreds = self.ageNet.forward()
        age = self.ageList[agePreds[0].argmax()]

        return gender, age